//
//  AuthFilters+extension.swift
//  ServerPackageDescription
//
//  Created by ping Cheng on 2017/10/26.
//
import PerfectSession
import PerfectHTTP
import PerfectLogger



extension  AuthFilter{

    public static func filterRoutes() -> HTTPRequestFilter {
        struct filterRequest: HTTPRequestFilter {
            
            func filter(request: HTTPRequest, response: HTTPResponse, callback: (HTTPRequestFilterResult) -> ()) {
                
                LogFile.debug("权限过滤")
                
                let checkAuth = AuthFilter.shouldWeAccept(request.path)
                
                let token = request.header(.custom(name: "token")) ?? ""
                
                guard checkAuth else {
                     callback(.continue(request, response))
                     return
                }
                // 没有令牌获取令牌过期则直接返回错误提示
                if token.isEmpty{
                    let result = ResponseData.jsonData(resultCode: ResultCode.unauthorized, data: nil)
                    response.setBody(string: result)
                    response.setHeader(.contentType, value: ResponseData.contentType)
                    callback(.halt(request, response))
                    return
                }else{
                    let session =  sessionManager.resume(token: token)
                    if !session.isValid(request){
                        let result = ResponseData.jsonData(resultCode: ResultCode.inValidateToken, data: nil)
                        response.setBody(string: result)
                        response.setHeader(.contentType, value: ResponseData.contentType)
                        callback(.halt(request, response))
                        return
                    }
                }
                
                callback(.continue(request, response))
            }
        }
        return filterRequest()
    }
    
}


